package com.chatToolsRpc.client;

import com.chatTools.protocol.MessageCodecSharable;
import com.chatTools.protocol.ProtocolFrameDecoder;
import com.chatToolsRpc.handler.RpcResponseMessageHandler;
import com.chatToolsRpc.message.RpcRequestMessage;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author： pang-yun
 * @date： 2021-09-22 17:51
 * 功能目的 ：用于 rpc 客户端
 */

@Slf4j
public class RpcClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler();
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();

        // rpc 响应消息处理器  待实现
        RpcResponseMessageHandler RPC_HANDLER = new RpcResponseMessageHandler();

        try {
            ChannelFuture channelFuture = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ProtocolFrameDecoder());
                            ch.pipeline().addLast(LOGGING_HANDLER);
                            ch.pipeline().addLast(MESSAGE_CODEC);
                            ch.pipeline().addLast(RPC_HANDLER);
                        }
                    }).connect("localhost", 9999).sync();
            Channel channel = channelFuture.channel();

            channel.writeAndFlush(new RpcRequestMessage(1,
                    "com.chatToolsRpc.server.service.HelloService",
                    "sayHello",
                    String.class,
                    new Class[]{String.class},
                    new Object[]{"hello, world!"}))
            .addListener(promise->{
                if (!promise.isSuccess()){
                    Throwable cause = promise.cause();
                    log.error("error",cause);
                }
            });

            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
